package com.audaque.springboot.foshanupload.cloudclient.interceptor;


import com.audaque.springboot.foshanupload.cloudclient.properties.CloudProperties;
import com.audaque.springboot.foshanupload.cloudcore.constants.CloudConst;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.audaque.springboot.foshanupload.core.result.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zgb
 * @desc ...
 * @date 2023-08-01 17:51:34
 */
@Slf4j
public class GatewayNeedInterceptor implements HandlerInterceptor {

  @Autowired
  private ObjectMapper objectMapper;

  @Autowired
  private CloudProperties cloudProperties;

  @Override
  public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {

	if (!cloudProperties.getOnlyFetchByGateway()) {
	  return true;
	}

	String header = request.getHeader(CloudConst.FROM_GATEWAY_HEADER_KEY);

	String encodeValue = new String(Base64Utils.encode(CloudConst.FROM_GATEWAY_HEADER_KEY.getBytes()));

	if (StringUtils.equals(encodeValue, header)) {
	  return true;
	} else {
	  R<String> r = new R<>();
	  r.setSuccess(false);
	  r.setCode(ResultCodeEnum.FAILE.getCode());
	  r.setMsg("请通过网关访问资源");


	  response.setContentType("application/json;charset=utf-8");
	  PrintWriter out = null;
	  try {
		out = response.getWriter();
	  } catch (IOException e) {
		throw new RuntimeException(e);
	  }

	  try {
		out.write(objectMapper.writeValueAsString(r));
		out.flush();
		out.close();
	  } catch (Exception e) {
		e.printStackTrace();
		log.error(e.getMessage());
	  }


	  return false;
	}
  }


}
